<template>
  <div>
    <div class="map-component-line">
      <span
        v-for="(item, index) in lines"
        :key="index"
        :data-id="item.id"
        :class="'map-component-line-item '+ (item.active ? 'active' : '')"
        @click="selectItem(index)"
      >
        <el-badge :value="12" class="item">
          <span>{{ item.name }}</span>
        </el-badge>
      </span>
      <el-button type="primary" icon="el-icon-plus" style="margin-left: 10px;" @click="clickLineAdd">添加线路</el-button>
    </div>

    <!--添加线路dialog-->
    <el-dialog title="添加线路" width="400px" :visible.sync="showLineAdd" :before-close="close">
      <el-form ref="addLineForm" :model="lineForm" :rules="rules">
        <el-form-item label="线路名称：" prop="addName">
          <el-input v-model="lineForm.addName" size="large" placeholder="请填写您要添加的线路名称" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="confirmAddLine">确定</el-button>
        <el-button type="default" @click="close">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showLineAdd: false,
      lineForm: {},
      lines: [
        {
          id: 1,
          name: '第一条线路'
        },
        {
          id: 2,
          name: '第二条线路'
        },
        {
          id: 3,
          name: '第三条线路'
        }
      ],
      rules: {
        addName: [
          { required: true, message: '请填写线路名称', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    /**
     * 添加线路
     */
    clickLineAdd() {
      this.showLineAdd = true
    },

    /**
     * 添加线路确认
     */
    confirmAddLine() {
      this.$refs['addLineForm'].validate((result) => {
        if (result) {
          const obj = {
            id: this.lines[this.lines.length],
            name: this.lineForm.addName
          }
          this.lines.push(obj)
          this.close()
        }
      })
    },

    /**
     * 关闭弹窗
     */
    close() {
      this.showLineAdd = false
      this.$refs['addLineForm'].resetFields()
    },

    /**
     * 点击地图上的线路菜单
     */
    selectItem(index) {
      this.lines.forEach((item, i) => {
        if (index === i) {
          this.$set(item, 'active', true)
        } else {
          this.$set(item, 'active', false)
        }
      })
    }
  }
}
</script>
